package com.wanglibao.woodtrade.woodtrade.ui.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.NumberKeyListener;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.wanglibao.woodtrade.woodtrade.R;
import com.wanglibao.woodtrade.woodtrade.config.NetConfig;
import com.wanglibao.woodtrade.woodtrade.entity.CommodityEntity;
import com.wanglibao.woodtrade.woodtrade.jsonrpc.JsonRPCAsyncTask;
import com.wanglibao.woodtrade.woodtrade.model.User;
import com.wanglibao.woodtrade.woodtrade.model.impl.UserImpl;
import com.wanglibao.woodtrade.woodtrade.ui.activity.user.LoginActivity;
import com.wanglibao.woodtrade.woodtrade.ui.fragment.adapter.HomepageBannerViewPager;
import com.wanglibao.woodtrade.woodtrade.util.CallPhone;
import com.wanglibao.woodtrade.woodtrade.util.ToastUtil;

import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.text.DecimalFormat;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CommodityActivity extends BaseActivity {

    @Bind(R.id.vp_activity_commodity_imglist)
    ViewPager vp_activity_commodity_imglist;

    @Bind(R.id.sv_activity_commodity)
    ScrollView sv_activity_commodity;

    @Bind(R.id.tv_activity_commodity_commtitle)
    TextView tv_activity_commodity_commtitle;

    @Bind(R.id.tv_activity_commodity_price)
    TextView tv_activity_commodity_price;

    @Bind(R.id.tv_activity_commodity_phone)
    TextView tv_activity_commodity_phone;

    @Bind(R.id.rl_common_title)
    RelativeLayout rl_common_title;

    @Bind(R.id.tv_activity_commodity_category_name)
    TextView tv_activity_commodity_category_name;

    @Bind(R.id.tv_activity_commodity_size)
    TextView tv_activity_commodity_size;

    @Bind(R.id.tv_activity_commodity_rank)
    TextView tv_activity_commodity_rank;

    @Bind(R.id.tv_activity_commodity_place)
    TextView tv_activity_commodity_place;

    @Bind(R.id.tv_activity_commodity_quantity)
    TextView tv_activity_commodity_quantity;

    @Bind(R.id.tv_activity_commodity_depot)
    TextView tv_activity_commodity_depot;

    @Bind(R.id.tv_activity_commodity_order_number)
    TextView tv_activity_commodity_order_number;

    @Bind(R.id.tv_activity_commodity_detail)
    TextView tv_activity_commodity_detail;

    @Bind(R.id.tv_activity_commodity_shop_name)
    TextView tv_activity_commodity_shop_name;

    @Bind(R.id.tv_activity_commodity_sentorder)
    TextView tv_activity_commodity_sentorder;

    @Bind(R.id.img_activity_commodity_shop_icon)
    ImageView img_activity_commodity_shop_icon;

    @Bind(R.id.ll_activity_commodity_dot)
    LinearLayout ll_activity_commodity_dot;

    @Bind(R.id.tv_activity_commodity_goods_click)
    TextView tv_activity_commodity_goods_click;

    CommodityEntity commodityEntity;

    Dialog dialog;

    double orderNumber;
    double size;

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if(msg.arg2!=2){
                if (msg.arg2 != 2) {
                    if (msg.arg1 == NetConfig.TaskId.detail){
                        commodityEntity = new Gson().fromJson(msg.obj.toString(), CommodityEntity.class);
                        showView();
                    }else if (msg.arg1 == NetConfig.TaskId.create_order){
                        if (dialog != null && dialog.isShowing()){
                            dialog.dismiss();
                        }
                        ToastUtil.createLongToast(CommodityActivity.this,"下单成功");
                        startActivity(new Intent(CommodityActivity.this,MyOrderActivity.class));
                        finish();
                    }
                }
            }
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_commodity);
        ButterKnife.bind(this);
        if (Build.VERSION.SDK_INT >= 19) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        } else {
            rl_common_title.setPadding(0, 0, 0, 0);
        }
        initView();
    }

    @OnClick(R.id.tl_activity_commodity_shop) void openShopClick(){
        if (!TextUtils.isEmpty(commodityEntity.getStore_id())){
            Intent intent = new Intent(this,ShopActivity.class);
            intent.putExtra("id",commodityEntity.getStore_id());
            startActivity(intent);
        }else {
            ToastUtil.createLongToast(this,"页面加载失败");
        }
    }

    private void initView() {
        addViewClicklistener(tv_activity_commodity_phone, tv_activity_commodity_sentorder,
                tvBack);

        String id = getIntent().getStringExtra("id");
        loadData(id);
        tvTitle.setText("商品详情");
    }

    public void showView(){
        tv_activity_commodity_commtitle.setText(commodityEntity.getTitle());
        tv_activity_commodity_price.setText("￥"+commodityEntity.getPrice()+"元/"+commodityEntity.getUnit_name());
        tv_activity_commodity_category_name.setText(commodityEntity.getGoods_name());
        tv_activity_commodity_size.setText(commodityEntity.getSize());
        tv_activity_commodity_rank.setText(commodityEntity.getRank());
        tv_activity_commodity_place.setText(commodityEntity.getCategory_name());
        tv_activity_commodity_quantity.setText(commodityEntity.getUp_quantity()+commodityEntity.getUnit_name());
        tv_activity_commodity_depot.setText(commodityEntity.getDepot());
        tv_activity_commodity_order_number.setText(commodityEntity.getOrder_number()+commodityEntity.getUnit_name());
        tv_activity_commodity_detail.setText(commodityEntity.getGoods_description());
        tv_activity_commodity_shop_name.setText(commodityEntity.getCompany());
        tv_activity_commodity_goods_click.setText("热度: "+commodityEntity.getGoods_click());

        HomepageBannerViewPager homepageBannerViewPager = new HomepageBannerViewPager(this,vp_activity_commodity_imglist,commodityEntity.getImg_url(),ll_activity_commodity_dot);
        homepageBannerViewPager.initScrollView();
        String url = commodityEntity.getLogo_img_url();
        ImageOptions imageOptions = new ImageOptions.Builder().setLoadingDrawable(getResources().getDrawable(R.mipmap.ic_lose_p_loading))
                .setFailureDrawable(getResources().getDrawable(R.mipmap.ic_lose_p_fail)).
                        setCircular(true).build();
        x.image().bind(img_activity_commodity_shop_icon,url,imageOptions);

    }

    /*操作权限的动态请求*/
    public void requestPermission() {
        //判断当前Activity是否已经获得了该权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            //如果App的权限申请曾经被用户拒绝过，就需要在这里跟用户做出解释
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CALL_PHONE)) {
                Toast.makeText(this, "please give me the permission", Toast.LENGTH_SHORT).show();
            } else {
                //进行权限请求
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, 10);
            }
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_activity_commodity_sentorder:
                if (new UserImpl(this).isLogin()){
                    showDialog();
                }else{
                    startActivity(new Intent(this, LoginActivity.class));
                }
                break;
            case R.id.tv_activity_commodity_phone:
                if (new UserImpl(this).isLogin()){
                    requestPermission();
                    CallPhone.call(commodityEntity.getMobile(),this);
                }else{
                    startActivity(new Intent(this, LoginActivity.class));
                }

                break;
        }
    }



    private void showDialog() {
        orderNumber = Double.parseDouble(commodityEntity.getOrder_number());
        size = Double.parseDouble(commodityEntity.getUp_quantity());
        if (orderNumber == 0)orderNumber = 1;
        if (size == 0)size = 1;
        if (dialog != null && dialog.isShowing()) return;
        dialog = new Dialog(this, R.style.dialog_bgTransparent);
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
        dialog.getWindow().setContentView(R.layout.dialog_activity_commodity_sentorder);
        TextView tv_dialog_activity_commodity_type = (TextView) dialog.findViewById(R.id.tv_dialog_activity_commodity_type);
        tv_dialog_activity_commodity_type.setText(commodityEntity.getCategory_name());
        TextView tv_dialog_activity_commodity_price = (TextView) dialog.findViewById(R.id.tv_dialog_activity_commodity_price);
        tv_dialog_activity_commodity_price.setText(commodityEntity.getPrice()+"元/"+commodityEntity.getUnit_name());
        TextView button = (TextView) dialog.findViewById(R.id.tv_dialog_activity_commodity_close);
        TextView tv_dialog_activity_commodity_quantity = (TextView) dialog.findViewById(R.id.tv_dialog_activity_commodity_quantity);
        tv_dialog_activity_commodity_quantity.setText("库存"+size+commodityEntity.getUnit_name());
        final TextView tv_dialog_activity_commodity_count = (TextView) dialog.findViewById(R.id.tv_dialog_activity_commodity_count);
        double priceCount = Double.parseDouble(commodityEntity.getPrice())*orderNumber;
        DecimalFormat df = new DecimalFormat("######0.00");
        tv_dialog_activity_commodity_count.setText("总价:" + df.format(priceCount) + "元");
        Button btn_layout_commodity_sentorder_size_reduce = (Button) dialog.findViewById(R.id.btn_layout_commodity_sentorder_size_reduce);
        Button btn_layout_commodity_sentorder_size_plus = (Button) dialog.findViewById(R.id.btn_layout_commodity_sentorder_size_plus);
        final EditText edit_layout_commodity_sentorder_size_number = (EditText) dialog.findViewById(R.id.edit_layout_commodity_sentorder_size_number);

        edit_layout_commodity_sentorder_size_number.setKeyListener(new NumberKeyListener() {
            @Override
            protected char[] getAcceptedChars() {
                if ("吨".equals(commodityEntity.getUnit_name())){
                    return new char[]{'0','1','2','3','4','5','6','7','8','9','.'};
                }else{
                    return new char[]{'0','1','2','3','4','5','6','7','8','9'};
                }
            }
            @Override
            public int getInputType() {
                return InputType.TYPE_CLASS_NUMBER;
            }
        });
        if (!"吨".equals(commodityEntity.getUnit_name())){
            edit_layout_commodity_sentorder_size_number.setText((int)orderNumber+"");
        }else{
            DecimalFormat df1 = new DecimalFormat("######0.0");
            edit_layout_commodity_sentorder_size_number.setText(df1.format(orderNumber));
        }
        final double price = Double.parseDouble(commodityEntity.getPrice());
        edit_layout_commodity_sentorder_size_number.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(s)){
//                    if (s.toString().indexOf(".") != s.toString().lastIndexOf(".") || // 判断 . 不能出现两次
//                            s.toString().indexOf(".") == 0 ||
//                            (s.toString().indexOf(".") > 0 && (s.toString().length()-1 - s.toString().indexOf(".")) > 1) ||
//                            s.toString().length()-1 == s.toString().indexOf(".")){
//                        ToastUtil.createLongToast(CommodityActivity.this,"数据有误");
//                        return;
//                    }
                    double value = 0;
                    try {
                        value = Double.parseDouble(s.toString());
                        double priceCount = value * price;
                        DecimalFormat df = new DecimalFormat("######0.00");
                        tv_dialog_activity_commodity_count.setText("总价:" + df.format(priceCount) + "元");
                    }catch (NumberFormatException exception){}
                }
            }
        });
        btn_layout_commodity_sentorder_size_reduce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                double num = Double.parseDouble(edit_layout_commodity_sentorder_size_number.getText().toString());
                if (num > 0){
                    num--;
                }
                if (orderNumber > size){
                    ToastUtil.createLongToast(CommodityActivity.this,"库存不足");
                }else if (num < orderNumber){
                    ToastUtil.createLongToast(CommodityActivity.this,"不能少于起定量");
                    num++;
                }else{
                    double priceCount = num * price;
                    DecimalFormat df = new DecimalFormat("######0.00");
                    tv_dialog_activity_commodity_count.setText("总价:" + df.format(priceCount) + "元");

                    if (!"吨".equals(commodityEntity.getUnit_name())){
                        edit_layout_commodity_sentorder_size_number.setText((int)num+"");
                    }else{
                        DecimalFormat df1 = new DecimalFormat("######0.0");
                        edit_layout_commodity_sentorder_size_number.setText(df1.format(num));
                    }
                }


            }
        });
        btn_layout_commodity_sentorder_size_plus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                double num = Double.parseDouble(edit_layout_commodity_sentorder_size_number.getText().toString());
                if (num >= 0){
                    num++;
                }
                if (orderNumber > size){
                    ToastUtil.createLongToast(CommodityActivity.this,"库存不足");
                }else if (num > size){
                    ToastUtil.createLongToast(CommodityActivity.this,"不能大于起库存");
                    num--;
                }else{
                    double priceCount = num * price;
                    DecimalFormat df = new DecimalFormat("######0.00");
                    tv_dialog_activity_commodity_count.setText("总价:" + df.format(priceCount) + "元");

                    if (!"吨".equals(commodityEntity.getUnit_name())){
                        edit_layout_commodity_sentorder_size_number.setText((int)num+"");
                    }else{
                        DecimalFormat df1 = new DecimalFormat("######0.0");
                        edit_layout_commodity_sentorder_size_number.setText(df1.format(num));
                    }
                }

            }
        });
        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        TextView tv_dialog_activity_sentorder = (TextView) dialog.findViewById(R.id.tv_dialog_activity_sentorder);
        tv_dialog_activity_sentorder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String num = edit_layout_commodity_sentorder_size_number.getText().toString();
                if (TextUtils.isEmpty(num)){
                    ToastUtil.createLongToast(CommodityActivity.this,"请填写购买数量");
                }else if(num.indexOf(".") > 0 && (num.length()-1 - num.indexOf(".")) > 1){
                    ToastUtil.createLongToast(CommodityActivity.this,"只能有一位小数");
                }else if (num.indexOf(".") != num.lastIndexOf(".") || // 判断 . 不能出现两次
                        num.indexOf(".") == 0 ||
                        (num.indexOf(".") > 0 && (num.length()-1 - num.indexOf(".")) > 1) ||
                        num.length()-1 == num.indexOf(".")){
                    ToastUtil.createLongToast(CommodityActivity.this,"数量有误");
                }else if (orderNumber > size || Double.parseDouble(num) > size){
                    ToastUtil.createLongToast(CommodityActivity.this,"库存不足");
                }else if(Double.parseDouble(num) < orderNumber){
                    ToastUtil.createLongToast(CommodityActivity.this,"不能少于起定量");
                }else{
                    User user = new UserImpl(CommodityActivity.this).getUser();
                    //SERVER_wangliwei
                    JsonRPCAsyncTask jsonRPCAsyncTask = new JsonRPCAsyncTask(CommodityActivity.this,NetConfig.SERVER+NetConfig.TYPE_ORDER,
                            NetConfig.create_order,handler,"jsonObject",NetConfig.TaskId.create_order,
                            new Object[]{commodityEntity.getGoods_id(),edit_layout_commodity_sentorder_size_number.getText(),user.token});
                    jsonRPCAsyncTask.execute(new Void[]{});
                }
            }
        });
    }


   //SERVER_wangxiaoming
    void loadData(String id) {
        JsonRPCAsyncTask jsonRPCAsyncTask = new JsonRPCAsyncTask(this, NetConfig.SERVER + NetConfig.TYPE_GOODS,
                NetConfig.detail, handler, "jsonObject", NetConfig.TaskId.detail, new Object[]{id});
        jsonRPCAsyncTask.execute(new Void[]{});
    }
}
